import sys
from django.conf import settings
from satchmo_store.mail import NoRecipientsException, send_store_mail, send_store_mail_template_decorator
from django.core.mail import EmailMessage
from django.template import Context, loader, RequestContext
from product.models import Discount
from django.conf import settings
from django.utils.encoding import smart_str, smart_unicode
from satchmo_store.shop.signals import order_confirmation_sender
import logging

"""
A custom listener that will email an order when the status is set to billed
"""
from django.utils.translation import gettext_lazy as _

log = logging.getLogger('merch.listeners')

def EmailOnBilledStatus(sender, oldstatus="", newstatus="", order=None, template='', template_html='', **kwargs):
     log.debug('heard satchmo_order_status_changed, %s=>%s', oldstatus, newstatus)
     if oldstatus != 'Billed' and newstatus == 'Billed': 
        log.debug('sending fufilment notification')
        try:
            sale = Discount.objects.by_code(order.discount_code, raises=True)
        except Discount.DoesNotExist:
            sale = None
                
        c = Context({'order': order, 'sale' : sale})

        emails = []
        emails.append(settings.FULFILLMENT_EMAIL)

        try:
            t = loader.get_template('shop/email/order_fulfillment.txt')
            body = t.render(c)
            msg = EmailMessage("Order "+str(order.id)+": Ready for fulfillment", body, 'OWASP Event Management System <oems@owasp.org>', emails)
            msg.send()
        except:
            log.debug("error: ", sys.exc_info()[0])                